package com.tensquare.article.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import com.tensquare.entity.PageResult;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author tuzy
 */
@RestController
@RequestMapping("article")
public class ArticleController {


    @Autowired
    private ArticleService articleService;


    @GetMapping
    public Result findAll(){
        List<Article> all = articleService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",all);
    }

    @GetMapping("/{articleId}")
    public Result findById(@PathVariable String articleId){
        Article article = articleService.findById(articleId);
        return new Result(true,StatusCode.OK,"查询成功",article);
    }

    @PostMapping
    public Result addArticle(@RequestBody Article article){
        articleService.add(article);
        return new Result(true,StatusCode.OK,"新增成功");
    }


    @PutMapping("/{id}")
    public Result updateArticle(@PathVariable("id")String id,Article article){
        article.setId(id);
        articleService.update(article);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    @DeleteMapping("/{id}")
    public Result deleteArticle(@PathVariable("id")String id){
        articleService.delete(id);
        return new Result(true, StatusCode.OK,"删除成功");
    }

    //分页查询
    @PostMapping("/search/{page}/{size}")
    //之前接受文章数据，使用pojo,但是现在根据条件查询
    //而所有的条件都需要进行判断，遍历pojo的所有属性需要使用反射的方式，成本较高，性能较低。
    //直接使用集合的方式遍历，这里接受数据改为map集合
    public Result queryAndPage(@RequestBody Map<String,Object> map, @PathVariable Integer page, @PathVariable Integer size){
        Page<Article> page1 = articleService.search(map,page,size);
        return new Result(true,StatusCode.OK,"查询成功",new PageResult<>(page1.getTotal(),page1.getRecords()));
    }



}
